package com.huawei.hms.framework.network.restclient.dnkeeper;

import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.common.PLSharedPreferences;
import com.huawei.hms.framework.common.StringUtils;
import com.huawei.hms.framework.network.restclient.hianalytics.RequestFinishedInfo;
import com.huawei.hms.framework.network.restclient.hianalytics.RequestFinishedInfo.Metrics;
import com.huawei.hms.framework.network.restclient.hwhttp.HttpClientGlobalInstance;
import com.huawei.hms.framework.network.restclient.hwhttp.Request;
import com.huawei.hms.framework.network.restclient.hwhttp.Request.Builder;
import com.huawei.hms.framework.network.restclient.hwhttp.RequestBody;
import com.huawei.hms.framework.network.restclient.hwhttp.RequestExtraInfo;
import com.huawei.hms.framework.network.restclient.hwhttp.Response;
import com.huawei.hms.framework.network.restclient.hwhttp.Submit;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DnsResult;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DnsResult.Address;
import com.huawei.hms.framework.network.restclient.hwhttp.url.HttpUrl;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.json.JSONArray;
import org.json.JSONObject;

public class DNKeeperCallable implements Callable {
    private static final String TAG = "DNKeeperCallable";
    private String dnkeeperDomainName;
    private List<String> dnkeeperIp = new ArrayList();
    private String domain;
    private PLSharedPreferences preferences;
    private RequestHost requestHost;
    private RequestRecord requestRecord;

    public DNKeeperCallable(RequestHost requestHost, String str, RequestRecord requestRecord, PLSharedPreferences pLSharedPreferences) {
        this.requestHost = requestHost;
        this.domain = requestHost.getDomainName();
        this.dnkeeperDomainName = str;
        this.requestRecord = requestRecord;
        this.preferences = pLSharedPreferences;
    }

    public DnsResult call() {
        DnsResult dnsResult = new DnsResult();
        Request build = new Builder().url(new HttpUrl("https://" + this.dnkeeperDomainName + DNKeeperConfig.SUFFIX_NAME)).method("POST").requestBody(RequestBody.create(DNKeeperConfig.DNKEEPER_CONTENT_TYPE, StringUtils.str2Byte(DNKeeperUtil.getRequestStr(this.requestHost)))).build();
        Logger.v(TAG, "DNKeeperCallable call : " + build);
        Submit newSubmit = HttpClientGlobalInstance.getInstance().getHttpClient().newSubmit(build);
        try {
            Response execute = newSubmit.execute();
            build = newSubmit.request();
            queryOnComplete();
            if (execute.isOK() && this.dnkeeperDomainName.equals(this.domain)) {
                getDnkeeperIp(build);
                updateDnkeeperIP(null);
                try {
                    execute.close();
                } catch (Throwable e) {
                    Logger.w(TAG, "response close error", e);
                }
                return this.preferences != null ? DNKeeperUtil.parseResponse(this.preferences.getString(this.dnkeeperDomainName)) : dnsResult;
            } else {
                if (execute.isOK()) {
                    getDnkeeperIp(build);
                    onParseResults(execute);
                } else {
                    Logger.w(TAG, "response status code:" + execute.getCode());
                    try {
                        Logger.v(TAG, "response body:" + StringUtils.byte2Str(execute.getBody().bytes()));
                    } catch (Throwable e2) {
                        Logger.w(TAG, "dnkeeper lookup occur error", e2);
                    }
                    queryOnFailure();
                }
                dnsResult = this.requestRecord.getDnsResult();
                if (DNKeeperUtil.isIpListEmpty(dnsResult)) {
                    return dnsResult;
                }
                Logger.i(TAG, "queryIps from dnkeeper service success");
                this.requestRecord.setNeedUpdate(false);
                return dnsResult;
            }
        } catch (Throwable e3) {
            Logger.w(TAG, "IOException: ", e3);
            queryOnComplete();
            queryOnFailure();
            return dnsResult;
        }
    }

    private void onParseResults(Response response) {
        try {
            String byte2Str = StringUtils.byte2Str(response.getBody().bytes());
            Logger.v(TAG, "response = " + byte2Str);
            JSONObject jSONObject = new JSONObject(byte2Str);
            if (jSONObject.getInt("atnCode") == 0) {
                jSONObject.put("createTime", System.currentTimeMillis());
                DnsResult parseResponse = DNKeeperUtil.parseResponse(jSONObject.toString());
                if (parseResponse != null) {
                    this.requestRecord.setDnsResult(parseResponse);
                    updateDnkeeperIP(parseResponse);
                    updateDnkeeperIP(null);
                    return;
                }
                queryOnFailure();
                return;
            }
            queryOnFailure();
        } catch (Throwable e) {
            queryOnFailure();
            Logger.w(TAG, "JSONException", e);
        } catch (Throwable e2) {
            queryOnFailure();
            Logger.w(TAG, "IOException", e2);
        }
    }

    private void updateDnkeeperIP(DnsResult dnsResult) {
        int i = 0;
        Logger.i(TAG, "dnkeeper result upDateIP");
        if (this.preferences != null) {
            this.preferences.putString(DNKeeperConfig.DNKEEPER_SP, "https://" + this.dnkeeperDomainName);
        }
        JSONArray jSONArray;
        if (dnsResult == null) {
            try {
                if (this.dnkeeperIp != null && !this.dnkeeperIp.isEmpty()) {
                    JSONObject jSONObject = new JSONObject();
                    jSONObject.put("type", "A");
                    jSONArray = new JSONArray();
                    int size = this.dnkeeperIp.size();
                    while (i < size) {
                        DNKeeperUtil.getArrayaddress(jSONArray, i, "A", (String) this.dnkeeperIp.get(i), 0);
                        i++;
                    }
                    jSONObject.put("addressList", jSONArray);
                    jSONObject.put("createTime", System.currentTimeMillis());
                    if (this.preferences != null) {
                        this.preferences.putString(this.dnkeeperDomainName, jSONObject.toString());
                    }
                    Logger.i(TAG, "dnkeeper ip result");
                    return;
                }
                return;
            } catch (Throwable e) {
                Logger.w(TAG, "fail to JSONException:", e);
                return;
            }
        }
        List addressList = dnsResult.getAddressList();
        if (addressList != null && addressList.size() != 0) {
            try {
                JSONObject jSONObject2 = new JSONObject();
                jSONObject2.put("type", "A");
                jSONArray = new JSONArray();
                int size2 = addressList.size();
                while (i < size2) {
                    DNKeeperUtil.getArrayaddress(jSONArray, i, ((Address) addressList.get(i)).getType(), ((Address) addressList.get(i)).getValue(), ((Address) addressList.get(i)).getTtl());
                    i++;
                }
                jSONObject2.put("addressList", jSONArray);
                jSONObject2.put("createTime", System.currentTimeMillis());
                if (this.preferences != null) {
                    this.preferences.putString(this.domain, jSONObject2.toString());
                }
            } catch (Throwable e2) {
                Logger.w(TAG, "fail to JSONException:", e2);
            }
            Logger.i(TAG, "other ip result");
        }
    }

    private void queryOnFailure() {
        this.requestRecord.setRequestTime(System.currentTimeMillis());
    }

    private void queryOnComplete() {
        this.requestRecord.setFuture(null);
    }

    private void getDnkeeperIp(Request request) {
        if (request != null) {
            RequestExtraInfo requestExtraInfo = request.getRequestExtraInfo();
            if (requestExtraInfo != null) {
                RequestFinishedInfo requestFinishedInfo = requestExtraInfo.getRequestFinishedInfo();
                if (requestFinishedInfo != null) {
                    Metrics metrics = requestFinishedInfo.getMetrics();
                    if (metrics != null) {
                        this.dnkeeperIp = metrics.getConnectIps();
                    }
                }
            }
        }
    }
}
